package oop.data;

import java.sql.SQLException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import oop.db.dao.CategoryDAO;

public class Category extends SimpleCategory {

	private Integer parentId;
	private Category parent;
	private boolean parentFetched = false;
	private List<Category> children = null;

	public Category() {
		// default constructor
	}

	public Category(int id, String name, Integer parentId) {
		super(id, name);
		this.parentId = parentId;
	}

	public void setParent(Category parent) {
		this.parent = parent;
		parentFetched = true;
		parentId = (parent == null ? null : parent.id);
	}

	public Set<Category> getAncestors() {
		Set<Category> ancestors = new HashSet<Category>();
		getAncestorsRecursive(ancestors, this);
		return ancestors;
	}
	
	private void getAncestorsRecursive(Set<Category> ancestors, Category curr) {
		if (curr == null) {
			return;
		}
		ancestors.add(curr);
		getAncestorsRecursive(ancestors, curr.getParent());
	}
	
	public Category getParent() {
		if (!parentFetched) {
			try {
				List<Category> categories = CategoryDAO.fetchById(getParentId());
				if (!categories.isEmpty()) {
					parent = categories.get(0);
				}
			} catch (SQLException e) {
				throw new RuntimeException(e);
			}
			parentFetched = true;
		}
		return parent;
	}

	public List<Category> getChildren() {
		if (children == null) {
			try {
				children = CategoryDAO.fetchByParent(id);
			} catch (SQLException e) {
				throw new RuntimeException(e);
			}
		}
		return children;
	}

	public void setParentId(Integer parentId) {
		this.parentId = parentId;
		parentFetched = false;
	}

	public Integer getParentId() {
		return parentId;
	}
	
	@Override
	public int hashCode() {
		return id;
	}
	
	@Override
	public boolean equals(Object obj) {
		if (obj instanceof Category) {
			return id == ((SimpleCategory) obj).id;
		}
		return false;
	}

}